const Moment = require('moment');
const MomentRange = require('moment-range');
const moment = MomentRange.extendMoment(Moment);
const Promise = require('bluebird');

/**
 * @api {get} /api/admin/v1/analyse/dashboard 控制面板
 * @apiGroup AdminAnalyse
 * @apiDescription 统计分析-控制面板
 * @apiPermission 管理员(查看统计分析)
 * @apiVersion 1.0.0
 */
exports.dashboard = function ({}, {models: {sequelize}}) {
    let today = moment().format('YYYY-MM-DD') + ' 00:00:00';
    let yesterday = moment().subtract(1, 'days').format('YYYY-MM-DD');
    let last7days = moment().subtract(7, 'days').format('YYYY-MM-DD') + ' 00:00:00';
    let last30days = moment().subtract(30, 'days').format('YYYY-MM-DD') + ' 00:00:00';
    return Promise.props({
        orders: Promise.props({
            today: sequelize.query("select count(*) count, ifnull(sum(feeString),0) as feeString, ifnull(sum(totalAlipayFeeString),0) as totalAlipayFeeString from TaokeOrders where payStatus in ('订单付款', '订单结算') and created_at > :begin", {
                type: sequelize.QueryTypes.SELECT,
                replacements: {begin: moment(today).toDate()}
            }).then(function (rows) {
                return rows[0];
            }),
            yesterday: sequelize.query("select count(*) count, ifnull(sum(feeString),0) as feeString, ifnull(sum(totalAlipayFeeString),0) as totalAlipayFeeString from TaokeOrders where payStatus in ('订单付款', '订单结算') and created_at between :begin and :end", {
                type: sequelize.QueryTypes.SELECT,
                replacements: {
                    begin: moment(yesterday + ' 00:00:00').toDate(),
                    end: moment(yesterday + ' 23:59:59').toDate()
                }
            }).then(function (rows) {
                return rows[0];
            }),
            last7days: sequelize.query("select count(*) count, ifnull(sum(feeString),0) as feeString, ifnull(sum(totalAlipayFeeString),0) as totalAlipayFeeString from TaokeOrders where payStatus in ('订单付款', '订单结算') and created_at > :begin", {
                type: sequelize.QueryTypes.SELECT,
                replacements: {begin: moment(last7days).toDate()}
            }).then(function (rows) {
                return rows[0];
            }),
            last30days: sequelize.query("select count(*) count, ifnull(sum(feeString),0) as feeString, ifnull(sum(totalAlipayFeeString),0) as totalAlipayFeeString from TaokeOrders where payStatus in ('订单付款', '订单结算') and created_at > :begin", {
                type: sequelize.QueryTypes.SELECT,
                replacements: {begin: moment(last30days).toDate()}
            }).then(function (rows) {
                return rows[0];
            })
        }),
        users: Promise.props({
            today: sequelize.query("select count(*) count from Users where created_at > :begin", {
                type: sequelize.QueryTypes.SELECT,
                replacements: {begin: moment(today).toDate()}
            }).then(function (rows) {
                return rows[0];
            }),
            yesterday: sequelize.query("select count(*) count from Users where created_at between :begin and :end", {
                type: sequelize.QueryTypes.SELECT,
                replacements: {
                    begin: moment(yesterday + ' 00:00:00').toDate(),
                    end: moment(yesterday + ' 23:59:59').toDate()
                }
            }).then(function (rows) {
                return rows[0];
            }),
            last7days: sequelize.query("select count(*) count from Users where created_at > :begin", {
                type: sequelize.QueryTypes.SELECT,
                replacements: {begin: moment(last7days).toDate()}
            }).then(function (rows) {
                return rows[0];
            }),
            last30days: sequelize.query("select count(*) count from Users where created_at > :begin", {
                type: sequelize.QueryTypes.SELECT,
                replacements: {begin: moment(last30days).toDate()}
            }).then(function (rows) {
                return rows[0];
            })
        }),
        agencys: Promise.props({
            today: sequelize.query("select count(*) count from Users where level = 'Agency' and created_at > :begin", {
                type: sequelize.QueryTypes.SELECT,
                replacements: {begin: moment(today).toDate()}
            }).then(function (rows) {
                return rows[0];
            }),
            yesterday: sequelize.query("select count(*) count from Users where level = 'Agency' and created_at between :begin and :end", {
                type: sequelize.QueryTypes.SELECT,
                replacements: {
                    begin: moment(yesterday + ' 00:00:00').toDate(),
                    end: moment(yesterday + ' 23:59:59').toDate()
                }
            }).then(function (rows) {
                return rows[0];
            }),
            last7days: sequelize.query("select count(*) count from Users where level = 'Agency' and created_at > :begin", {
                type: sequelize.QueryTypes.SELECT,
                replacements: {begin: moment(last7days).toDate()}
            }).then(function (rows) {
                return rows[0];
            }),
            last30days: sequelize.query("select count(*) count from Users where level = 'Agency' and created_at > :begin", {
                type: sequelize.QueryTypes.SELECT,
                replacements: {begin: moment(last30days).toDate()}
            }).then(function (rows) {
                return rows[0];
            })
        }),
        withdraws: Promise.props({
            today: sequelize.query("select count(*) count, ifnull(sum(total_amount),0) as total_amount from UsersWithdraws where created_at > :begin", {
                type: sequelize.QueryTypes.SELECT,
                replacements: {begin: moment(today).toDate()}
            }).then(function (rows) {
                return rows[0];
            }),
            yesterday: sequelize.query("select count(*) count, ifnull(sum(total_amount),0) as total_amount from UsersWithdraws where created_at between :begin and :end", {
                type: sequelize.QueryTypes.SELECT,
                replacements: {
                    begin: moment(yesterday + ' 00:00:00').toDate(),
                    end: moment(yesterday + ' 23:59:59').toDate()
                }
            }).then(function (rows) {
                return rows[0];
            }),
            last7days: sequelize.query("select count(*) count, ifnull(sum(total_amount),0) as total_amount from UsersWithdraws where created_at > :begin", {
                type: sequelize.QueryTypes.SELECT,
                replacements: {begin: moment(last7days).toDate()}
            }).then(function (rows) {
                return rows[0];
            }),
            last30days: sequelize.query("select count(*) count, ifnull(sum(total_amount),0) as total_amount from UsersWithdraws where created_at > :begin", {
                type: sequelize.QueryTypes.SELECT,
                replacements: {begin: moment(last30days).toDate()}
            }).then(function (rows) {
                return rows[0];
            })
        })
    });
}

/**
 * @api {get} /api/admin/v1/analyse/orders_data 订单制图数据
 * @apiGroup AdminAnalyse
 * @apiDescription 统计分析-订单制图数据
 * @apiPermission 管理员(查看统计分析)
 * @apiVersion 1.0.0
 */
exports.ordersData = function ({}, {models: {sequelize}}) {
    let begin = moment().add(-14, 'days'), end = moment();
    return sequelize.query("select tao_user, DATE_FORMAT(created_at,'%Y%m%d') as days, count(*) count, sum(feeString) as feeString, sum(totalAlipayFeeString) as totalAlipayFeeString from TaokeOrders where payStatus in ('订单付款', '订单结算') and created_at between :begin and :end group by tao_user, DATE_FORMAT(created_at,'%Y%m%d')", {
        type: sequelize.QueryTypes.SELECT,
        replacements: {
            begin: begin.toDate(),
            end: end.toDate()
        }
    }).then(function (rows) {
        let users = [], usersMap = {}, rowsMap = {};
        let countData = {
            labels: [],
            datasets: {}
        }
        let feeStringData = {
            labels: [],
            datasets: {}
        }
        let totalAlipayFeeStringData = {
            labels: [],
            datasets: {}
        }

        for (let i in rows) {
            let row = rows[i];
            if (row.tao_user) {
                if (!usersMap[row.tao_user]) {
                    usersMap[row.tao_user] = true;
                    users.push(row.tao_user);
                    countData.datasets[row.tao_user] = [];
                    feeStringData.datasets[row.tao_user] = [];
                    totalAlipayFeeStringData.datasets[row.tao_user] = [];
                }
                rowsMap[row.tao_user + '_' + row.days] = row;
            }
        }

        let range = moment.range(begin, end);
        for (let month of range.reverseBy('days')) {
            let label = month.format('YYYYMMDD');
            countData.labels.push(label);
            feeStringData.labels.push(label);
            totalAlipayFeeStringData.labels.push(label);
            for (let i in users) {
                let user = users[i];
                let row = rowsMap[user + '_' + label];
                countData.datasets[user].push(row && row.count || 0);
                feeStringData.datasets[user].push(row && row.feeString || 0);
                totalAlipayFeeStringData.datasets[user].push(row && row.totalAlipayFeeString || 0);
            }
        }

        return {
            countData: countData,
            feeStringData: feeStringData,
            totalAlipayFeeStringData: totalAlipayFeeStringData
        };
    });
}

/**
 * @api {get} /api/admin/v1/analyse/users_data 用户制图数据
 * @apiGroup AdminAnalyse
 * @apiDescription 统计分析-用户制图数据
 * @apiPermission 管理员(查看统计分析)
 * @apiVersion 1.0.0
 */
exports.usersData = function ({}, {models: {sequelize}}) {
    let begin = moment().add(-14, 'days'), end = moment();
    return sequelize.query("select partner_id, DATE_FORMAT(created_at,'%Y%m%d') as days, count(*) count from Users where created_at between :begin and :end group by partner_id, DATE_FORMAT(created_at,'%Y%m%d')", {
        type: sequelize.QueryTypes.SELECT,
        replacements: {
            begin: begin.toDate(),
            end: end.toDate()
        }
    }).then(function (rows) {
        let users = [], usersMap = {}, rowsMap = {};
        let countData = {
            labels: [],
            datasets: {}
        }

        for (let i in rows) {
            let row = rows[i];
            if (row.partner_id) {
                if (!usersMap[row.partner_id]) {
                    usersMap[row.partner_id] = true;
                    users.push(row.partner_id);
                    countData.datasets[row.partner_id] = [];
                }
                rowsMap[row.partner_id + '_' + row.days] = row;
            }
        }

        let range = moment.range(begin, end);
        for (let month of range.reverseBy('days')) {
            let label = month.format('YYYYMMDD');
            countData.labels.push(label);
            for (let i in users) {
                let user = users[i];
                let row = rowsMap[user + '_' + label];
                countData.datasets[user].push(row && row.count || 0);
            }
        }

        return {
            countData: countData
        };
    });
}

/**
 * @api {get} /api/admin/v1/analyse/withdraws_data 提现制图数据
 * @apiGroup AdminAnalyse
 * @apiDescription 统计分析-提现制图数据
 * @apiPermission 管理员(查看统计分析)
 * @apiVersion 1.0.0
 */
exports.withdrawsData = function ({}, {models: {sequelize}}) {
    let begin = moment().add(-14, 'days'), end = moment();
    return sequelize.query("select partner_id, DATE_FORMAT(created_at,'%Y%m%d') as days, count(*) count, sum(total_amount) as total_amount from UsersWithdraws where created_at between :begin and :end group by partner_id, DATE_FORMAT(created_at,'%Y%m%d')", {
        type: sequelize.QueryTypes.SELECT,
        replacements: {
            begin: begin.toDate(),
            end: end.toDate()
        }
    }).then(function (rows) {
        let users = [], usersMap = {}, rowsMap = {};
        let countData = {
            labels: [],
            datasets: {}
        }
        let totalAmountData = {
            labels: [],
            datasets: {}
        }

        for (let i in rows) {
            let row = rows[i];
            if (row.partner_id) {
                if (!usersMap[row.partner_id]) {
                    usersMap[row.partner_id] = true;
                    users.push(row.partner_id);
                    countData.datasets[row.partner_id] = [];
                    totalAmountData.datasets[row.partner_id] = [];
                }
                rowsMap[row.partner_id + '_' + row.days] = row;
            }
        }

        let range = moment.range(begin, end);
        for (let month of range.reverseBy('days')) {
            let label = month.format('YYYYMMDD');
            countData.labels.push(label);
            totalAmountData.labels.push(label);
            for (let i in users) {
                let user = users[i];
                let row = rowsMap[user + '_' + label];
                countData.datasets[user].push(row && row.count || 0);
                totalAmountData.datasets[user].push(row && row.total_amount || 0);
            }
        }

        return {
            countData: countData,
            totalAmountData: totalAmountData
        };
    });
}